from django.shortcuts import render,redirect,HttpResponse
from app01 import models
from app01.utils.code import check_code
from app01.utils.form import LoginModelForm
from io import BytesIO
def login(request):
    if request.method == 'GET':
        form = LoginModelForm()
        return  render(request,'login.html',{'form':form})
    form = LoginModelForm(data=request.POST)
    if form.is_valid():
        #校验验证码
        user_input_code=form.cleaned_data.pop('code')
        code=request.session.get('image_code')
        if code.upper()!=user_input_code.upper():
            form.add_error("code","验证码错误")
            return render(request, 'login.html', {'form': form})
        # 获取用户输入的用户名和密码的对象
        admin_object=models.Admin.objects.filter(**form.cleaned_data).first()
        #如果用户和密码在数据库没有
        if not admin_object:
            form.add_error("password","用户名或密码错误")
            return render(request, 'login.html', {'form': form})
        #如果用户和密码在数据库有
        #生成session
        request.session['info']={'id':admin_object.id,'name':admin_object.name}
        #设置session过期时间(保存7天)
        request.session.set_expiry(60*60*24*7)
        return  redirect('/admin/list/')

    else:
        return render(request, 'login.html', {'form': form})


def loginout(request):
    request.session.clear()
    return redirect('/login/')

def image_code(request):
    """
    生成图片二维码

    """
    img,code_str=check_code()
    # 写入session中
    request.session['image_code']=code_str
    #设置session超时
    request.session.set_expiry(60)
    stream=BytesIO()
    img.save(stream,'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())

